<template>
  <div>
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="5" style="height: 100%">
        <el-card style="height: 100%">
          <el-button-group circle style="margin-bottom: 5px">
            <el-button type="primary" icon="el-icon-plus" style="padding:8px" @click="openGroupAdd"></el-button>
            <el-button type="primary" icon="el-icon-edit" style="padding:8px" @click="openGroupEdit"></el-button>
            <el-button type="primary" icon="el-icon-delete" style="padding:8px" @click="deleteGroup"></el-button>
          </el-button-group>
          <el-input style="margin-bottom: 5px" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
          <el-tree
            v-loading="treeLoading"
            class="filter-tree tree-scroll"
            :data="groupTreeData"
            :props="defaultProps"
            node-key="nodeId"

            @node-click="handleNodeClick"
            highlight-current
            :expand-on-click-node="false"
            :default-expand-all="true"
            :filter-node-method="filterNode"
            ref="groupTree">
          </el-tree>
        </el-card> <!--:default-expanded-keys="[-1]"-->
      </el-col><!---->
      <el-col :span="19" style="padding-left: 0">
        <el-card>
          <el-form inline>
            <el-form-item label="名称:" class="mgb-0">
              <el-input v-model="fname"></el-input>
            </el-form-item>
            <el-form-item label="编码:" class="mgb-0">
              <el-input v-model="fnumber"></el-input>
            </el-form-item>
            <el-form-item label="仅主设备:" class="mgb-0">
              <el-switch v-model="fismain" active-color="primary"  inactive-color="info"  active-value="1" inactive-value="0"/>
            </el-form-item>
            <el-form-item class="mgb-0">
              <el-button type="primary" icon="el-icon-search" @click="searchData"></el-button>
              <el-button type="success" icon="el-icon-refresh" @click="clearData"></el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card style="margin-top: 10px">
          <div style="margin-bottom: 10px">
            <el-button type="primary" @click="openAdd">新增</el-button>
            <el-button type="success" @click="batchEnable(0)">启用</el-button>
            <el-button type="danger" @click="batchEnable(1)">禁用</el-button>
            <el-button type="danger" @click="batchRemove">删除</el-button>
            <el-button type="success" @click="batchPrint">标签打印</el-button>
          </div>
          <el-table border :data="dataList" v-loading="tableLoading" ref="iTable1" @row-click="handleRowClick">
            <el-table-column align="center" type="selection" width="55"></el-table-column>
            <el-table-column label="编码" prop="fnumber" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="名称" prop="fname" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="规格" prop="fmodel" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="车间" prop="fuseaddress" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="主设备" prop="fIsmain" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fismain ==0" type="danger">否</el-tag>
                <el-tag v-if="scope.row.fismain ==1" type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="关键设备" prop="fiskey" align="center"  show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fiskey ==0" type="danger">否</el-tag>
                <el-tag v-if="scope.row.fiskey ==1" type="success">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="fstatus" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-if="scope.row.fstatus ==0" type="success">启用</el-tag>
                <el-tag v-if="scope.row.fstatus ==1" type="danger">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click.stop="openDetail(scope.row.fid)">详情</el-button>
                <el-button type="text" v-if="scope.row.fstatus==1" @click.stop="openEdit(scope.row.fid)">编辑</el-button><!--v-if="scope.row.fstatus===1"-->

              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float:right; margin: 10px 0;" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[6,9,10, 15, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页" :total="totalRows">
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
    <!-- 设备新增 编辑-->   <!---->
    <facility-addEdit v-if="isShowFacilityAddEdit" :isview="isview" :fid="fid" :status="status" :fgroupid="fgroupId"  @close="closeAddEdit" @notRefresh="notRefresh"></facility-addEdit>
    <!-- 设备详情-->
    <facility-detail v-if="isShowDetail" :isview="isview" :fid="fid" @close="closeDetail"></facility-detail>
    <!--左树新增 -->
    <equipment-addEdit v-if="isShowGroupAddEdit" :groupId="fgroupId" :parentId="fparentgroupId" @close="closeGroupAddEdit" @notRefresh="groupNotRefresh"></equipment-addEdit>
    <!--详情-->
    <materialGroup-detail v-if="isShowGroupDetail" :groupId="fgroupId" :parentId="fparentgroupId" @close="closeGroupDetail"></materialGroup-detail>
    <!--标签打印-->
    <usb-print v-if="isShowPrint" @close="() => isShowPrint=false" fentityid="tie-mdm-MaterialResult" :fid="printIds"></usb-print>
  </div>
</template>

<script>
    import EquipmentGroupApi from "@/api/module/EquipmentGroupApi"
    import _ from "lodash";

    export default {
        name: "equipmentData",
        components: {
          //左树 新增 编辑
          equipmentAddEdit:resolve=> require(['./equipmentdata/tree_addEdit'],resolve),
          //设备新增 编辑
          facilityAddEdit: resolve => require(['./facility/facility_addEdit'], resolve),
          //设备详情
          facilityDetail: resolve => require(['./facility/facility_detail'], resolve),
        },
        data() {
          return {
            filterText: '',
            groupTreeData: [],
            fstatus:[],
            defaultProps: {
              children: 'children',
              label: 'nodeName'
            },
            fname: '',
            fnumber: '',
            fismain:'',
            fgroupId: 0,
            fparentgroupId: 0,
            treeLoading: false,
            tableLoading: false,
            dataList: [],
            page: 1, //当前页面
            pageSize: 9, // 当前页数
            totalRows: 0, // 总条数
            fid: 0,
            isShowFacilityAddEdit:false, //新增 编辑
            isShowGroupAddEdit: false,  //左树 新增 编辑
            isShowGroupDetail: false,
            isShowsupplierAddEdit: false,
            isShowDetail: false,   // 左树详情
            status: '',
            fmnemoniccode: null,
            fmodel: null,
            status: '',
            isShowPrint: false,
            printIds: [],
            http:new EquipmentGroupApi(),
          }
        },
        watch: {
            filterText (val) {
              this.$refs.groupTree.filter(val);
            }
        },
        async created(){
            this.treeLoading = true
            //let fstatus = await this.http.getEnum({sysName:"tie-demo",className:"cn.hxlc.tie.demo.core.enums.StatusEnum"})
            let groupTreeData = await this.http.groupTreeData()
            console.log(groupTreeData)
            this.groupTreeData = this.flatTurnTree(groupTreeData.data, 'nodeId', 'nodePid', -1)
            this.treeLoading = false
            this.getData();
          },

      methods: {
        flatTurnTree(list, id, parentId, topNode) {
          let temp = {}
          let ans = []
          for (let i in list) {
            temp[list[i][id]] = list[i]
          }
          for (let i in temp) {
            if (temp[i][parentId] != topNode && temp[i][id]) {
              if (!temp[temp[i][parentId]].children) {
                temp[temp[i][parentId]].children = new Array()
              }
              temp[temp[i][parentId]].children.push(temp[i])
            } else {
              ans.push(temp[i])
            }
          }
          if(ans.length !== 0 && !_.isArray(ans[0].children)){
            ans[0].children = []
          }
          return ans
        },
        batchPrint () {
          const _selectData = this.$refs.iTable1.selection
          if (_selectData.length == 0) {
            this.$tie.showError('请至少选择一条数据！')
            return
          }
          this.printIds = new Array();
          for (var i = 0; i < _selectData.length; i++) {
            this.printIds[i] = _selectData[i].fid;
          }
          this.isShowPrint = true
        },
        filterNode (value, data) {
          if (!value) return true;
          return data.nodeName.indexOf(value) !== -1;
        },
        handleNodeClick (val) {
          if (val.nodeId === -1) {
            this.fgroupId = 0
          } else {
            this.fgroupId = val.nodeId
          }
          this.page = 1
          this.getData()
        },
        //获取表格数据源
        getData () {
            this.tableLoading = true
            let data = {
              fname: this.fname,
              fnumber: this.fnumber,
              fismain: this.fismain,
              fgroupid: this.fgroupId,
              eparentid: this.eparentid,
              pageSize: this.pageSize,
              page: this.page,
            }
            this.http.queryListPage(data).then(res => {
              this.dataList = res.data.rows
              this.page = res.data.page
              this.pageSize = res.data.pageSize
              this.totalRows = res.data.totalRows
              this.tableLoading = false
            })
          },
        // 当前页码修改时
        handleCurrentChange (page) {
          this.page = page
          this.getData()
        },
        // 当前页数修改时
        handleSizeChange (pageSize) {
          this.pageSize = pageSize
          this.getData()
        },
        searchData () {
          this.page = 1
          this.getData()
        },
        clearData () {
          this.fname = null
          this.fnumber = null
          this.fmnemoniccode = null
          this.fmodel = null
        },
        //打开新增弹窗  设备新增
        openAdd () {
          /*if (!this.fgroupId) {
            this.$message.error('请选择分类!')
            return
          }*/
          this.fid = null
          this.isview = false
          this.status = 'addFacility'
          this.isShowFacilityAddEdit = true
        },
        //打开编辑弹窗  设备编辑
        openEdit (id) {
          console.log("设备编辑"+id)
          this.fid = id
          this.isview = true
          this.status = 'edit'
          this.isShowFacilityAddEdit = true
        },
        //关闭新增编辑弹窗
        closeAddEdit () {
          this.isShowFacilityAddEdit = false
          this.fid = ''
          this.getData()
        },
        notRefresh () {
          this.isShowFacilityAddEdit = false
          this.fid = ''
        },
        //打开详情弹窗
        openDetail (id) {
          this.fid = id
          this.isview = true
          this.status = 'view'
          this.isShowGroupAddEdit = true
        },
        //关闭详情弹窗
        closeDetail () {
          this.fid = ''
          this.isShowDetail = false
        },
        //打开详情弹窗  设备详情
        openDetail (id) {
          console.log("设备详情:"+id)
          this.fid = id
          this.isview = true
          this.isShowDetail = true
          this.status = 'view'
        },
        //关闭详情弹窗
        closeDetail () {
          this.fid = ''
          this.isShowDetail = false
          //this.isShowGroupAddEdit = false
        },
        //删除
        delete (id) {
          this.$confirm('此操作将永久删除该物料, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: `删除中，请耐心等待.....`,
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            this.http.delete({ fid }).then(res => {
              this.$message({ type: 'success', message: '删除成功!' })
              loading.close()
              this.getData()
            }).catch(e => {
              loading.close()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        },
        handleRowClick (row, column, event) {
          this.$refs.iTable1.toggleRowSelection(row)
        },
        //打开新增弹窗
        openGroupAdd () {
          if (!this.fgroupId || this.fgroupId == -1 || this.fgroupId == '-1') {
            this.$message.error('请选择分类!')
            return
          }
          if (!this.fgroupId) {
            this.fgroupId = -1;
          }
          let parentid = this.fgroupId
          this.fparentgroupId = parentid+''
          this.fgroupId = null
          this.$refs.groupTree.setCurrentKey()
          this.isShowGroupAddEdit = true
        },
        //打开左树编辑弹窗
        openGroupEdit (id) {
          if (!this.fgroupId || this.fgroupId == -1 || this.fgroupId == '-1') {
            this.$message.error('请选择分类!')
            return
          }
          this.isShowGroupAddEdit = true
        },
        //关闭左树新增编辑弹窗
        closeGroupAddEdit () {
          this.isShowGroupAddEdit = false
          this.fgroupId = null
          this.fparentgroupId = null
          this.refreshAll()
        },
        groupNotRefresh () {
          this.fparentgroupId = null
          this.isShowGroupAddEdit = false
        },
        //删除
        deleteGroup (id) {
          if (!this.fgroupId) {
            this.$message.error('请选择分类!')
            return
          }
          this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: `删除中，请耐心等待.....`,
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            let groupId = this.fgroupId
            this.http.delete({ fid: groupId }).then(res => {
              this.$tie.showSuccess(res.message)
              loading.close()
              this.refreshAll()
            }).catch(e => {
              loading.close()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
          this.refreshAll()
        },
        batchEnable (status) {
          console.log("run 启用 禁用")
          var fids = this.getSelectIdByTable();
          console.log(fids);
          if (fids.length == 0) {
            this.$message.error('未选中数据!')
          } else {
            const loading = this.$loading({
              lock: true,
              text: `批量操作中，请耐心等待.....`,
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            console.log(fids);
            this.http.batchChangeState({ "fid": fids, "fstatus": status }).then(res => {
              this.$tie.showSuccess(res.message)
              console.log("后台返回的结果:"+res.message)
              loading.close();
              this.getData();
            }).catch(e => {
              loading.close();
            })
          }
        }, batchRemove () {
          var fids = this.getSelectIdByTable();
          console.log("删除:"+fids)
          if (fids.length == 0) {
            this.$message.error('未选中数据!')
          } else {
            const loading = this.$loading({
              lock: true,
              text: `批量操作中，请耐心等待.....`,
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            this.http.batchDelete({ "fid": fids }).then(res => {
              this.$tie.showSuccess(res.message)
              loading.close();
              this.getData();
            }).catch(e => {
              loading.close();
            })
          }

        },
        getSelectIdByTable () {
          var batchChoose = this.$refs.iTable1.selection;
          var fids = [];
          for (var i = 0; i < batchChoose.length; i++) {
            fids[i] = batchChoose[i].fid;
          }
          return fids;
        },
        async refreshAll () {
          this.treeLoading = true
          this.groupTreeData = [];
          this.groupTreeData = await this.http.groupTreeData({});
          this.groupTreeData = this.flatTurnTree(this.groupTreeData.data, 'nodeId', 'nodePid', -1);
          this.treeLoading = false
          this.getData();
        },
      },

    }
</script>

<style scoped>

</style>
